<%@page language="java" contentType="text/html; charset=UTF-8" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="html" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<html:header title="选择商品">

    <link rel="stylesheet" href="${baseUrl}css/public.css" media="all">

    <style type="text/css">
        a{
            color: #01AAED;
            text-decoration: none;
            font-size: 12px;
        }
        a:hover {
            color: #FF5722;
        }

        .layui-table-view{
            margin: 0;
        }
        .layui-table-cell {
            overflow: visible !important;
        }
        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select{
            margin-top: -10px;
            margin-left: -15px;
            margin-right: -15px;
        }
    </style>

    <script>
        let houseId = "${houseId}";

        jQuery(function () {
            if ("${checkStock}" == "1") {
                //需要检查库存
                if (houseId == "") {
                    errTip("请选择仓库");
                    parent.layer.close(parent.layer.getFrameIndex(window.name));
                    return;
                }
            }

            console.log("showSn:${showSn}");
            ajaxSelect("${baseUrl}goods/type/getAll.action","typeId","商品分类");

            $("#cancel").click(function () {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });

        });

        layui.use(['form','table','layer'], function () {
            let $ = layui.jquery,
                form = layui.form,
                table = layui.table;

            $("#sure").click(function () {
                let data = [];
                for(let key in selected_map){
                    let d = selected_map[key];
                    if (d.number > 0) {
                        let amount  = d.number * d.price;
                        d.amount = (amount);
                        d.remark = "";
                        data.push(d);
                    }
                }

                window.parent.getSelectGoods(data);
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });

            // 监听修改update到表格中
            form.on('select(unitSelect)', function (data) {
                let elem = $(data.elem);
                let trElem = elem.parents('tr');
                let index = trElem.data('index');
                let tableData = table.cache.table;

                let goodsUnitVo;
                $.each(tableData[index].goodsUnitVoList, function (i, vo) {
                    if (vo.unitId == data.value) {
                        goodsUnitVo = vo;
                    }
                });

                let price = 0;
                <c:if test="${priceFlag==1}">
                price = goodsUnitVo.referBuyPrice;
                </c:if>
                <c:if test="${priceFlag==2}">
                price = goodsUnitVo.minPrice;
                </c:if>
                <c:if test="${priceFlag==3}">
                price = goodsUnitVo.wholesalePrice;
                </c:if>
                <c:if test="${priceFlag==4}">
                price = goodsUnitVo.retailPrice;
                </c:if>

                //处理对应的单价显示
                let $retailPrice = trElem.find(".price");
                $retailPrice.html(getPrice(price));

                //得到商品单位数据后的操作
                tableData[index].unitId = data.value;
                tableData[index].times = goodsUnitVo.times;
                tableData[index].price = price;
                let amount = parseFloat(tableData[index].price) * tableData[index].number;
                tableData[index].amount = (amount);

                <c:if test="${checkStock==1}">
                let stockNum = parseInt(tableData[index].baseStockNum/goodsUnitVo.times);
                tableData[index].stockNum = stockNum;
                elem.parents('tr').find(".stockNum").html(stockNum);

                if (stockNum < tableData[index].number) {
                    processNumber_select(true,stockNum, elem.parents("tr").find(".number"), true);
                }
                </c:if>
            });

            form.on('submit(search)', function (data) {
                table.reload('table',{
                    where: data.field
                    ,page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
                return false;
            });

            let url = "${baseUrl}goods/goods/";
            if("${checkStock}" == 1) {
                url += "getListWithStock.action?houseId=${houseId}";
            } else {
                url += "getList.action";
            }
            table.render({
                id:'table',
                elem: '#table',
                height:500,
                url: url,
                where : {
                    sn:"${sn}",
                    status :1,
                    time:(new Date()).valueOf()
                },
                cols: [[
                    {type:'numbers'},
                    {field: 'num', width: 100, title: '数量',templet: '#numberBar'},
                    {field: 'name', minWidth: 130, title: '名称/规格',style:"font-size:12px;",templet:function (d) {
                            return genGoodsName(d.name,d.norms);
                        }},
                    {field:'unit', width: 120, title: '单位',style:"font-size:12px;", templet:function (d) {
                            let sGoods = getSelectedById(d.id);
                            let unitId = sGoods==null ? null:sGoods.unitId;
                            return genSelectUnit(unitId, d.goodsUnitVoList);
                        }},

                    <c:if test="${priceFlag==1}">
                    {width: 120, title: '进货价',style:"font-size:12px;",templet: function(d){
                        let price = getSelectedById(d.id)==null ? d.goodsUnitVoList[0].referBuyPrice:getSelectedById(d.id).price;
                        return "<span class='price'>"+getPrice(price)+"</span>";
                    }},
                    </c:if>
                    <c:if test="${priceFlag==2}">
                    {width: 120, title: '最低售价',style:"font-size:12px;",templet: function(d){
                        let price = getSelectedById(d.id)==null ? d.goodsUnitVoList[0].minPrice:getSelectedById(d.id).price;
                        return "<span class='price'>"+getPrice(price)+"</span>";
                    }},
                    </c:if>
                    <c:if test="${priceFlag==3}">
                    {width: 120, title: '批发价',style:"font-size:12px;",templet: function(d){
                            let price = getSelectedById(d.id)==null ? d.goodsUnitVoList[0].wholesalePrice:getSelectedById(d.id).price;
                            return "<span class='price'>"+getPrice(price)+"</span>";
                        }},
                    </c:if>
                    <c:if test="${priceFlag==4}">
                    {width: 120, title: '零售价',style:"font-size:12px;",templet: function(d){
                            let price = getSelectedById(d.id)==null ? d.goodsUnitVoList[0].retailPrice:getSelectedById(d.id).price;
                            return "<span class='price'>"+getPrice(price)+"</span>";
                        }},
                    </c:if>

                    <c:if test="${checkStock==1}">
                    {width: 100, title: '库存',templet: function(d){
                        if (d.stockNum == null) {
                            return '<span class="stockNum">0</span>';
                        }
                        return '<span class="stockNum">'+d.stockNum+'</span>';
                    }},
                    </c:if>
                ]],
                limit: 10,
                page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                    //,curr: 5 //设定初始在第 5 页
                    ,groups: 5 //只显示 5 个连续页码
                    ,first: false //不显示首页
                    ,last: false //不显示尾页
                },
                done : function () {
                    let tableData = table.cache.table;
                    //初始化数据
                    layui.each(tableData, function (index, d) {
                        let selectedGoods = getSelectedById(d.id);
                        if (selectedGoods!=null){
                            tableData[index]=selectedGoods;
                        } else {
                            //库存
                            <c:if test="${checkStock == 1}">
                            if (d.stockNum == null) {
                                tableData[index].stockNum = 0;
                            }
                            tableData[index].baseStockNum = tableData[index].stockNum;
                            </c:if>

                            //其他
                            tableData[index].number = 0;
                            let price = 0 ;
                            <c:if test="${priceFlag==1}">
                            price = (tableData[index].goodsUnitVoList[0].referBuyPrice);
                            </c:if>
                            <c:if test="${priceFlag==2}">
                            price = (tableData[index].goodsUnitVoList[0].minPrice);
                            </c:if>
                            <c:if test="${priceFlag==3}">
                            price = (tableData[index].goodsUnitVoList[0].wholesalePrice);
                            </c:if>
                            <c:if test="${priceFlag==4}">
                            price = (tableData[index].goodsUnitVoList[0].retailPrice);
                            </c:if>
                            tableData[index].price = price;
                            tableData[index].amount = 0;
                            tableData[index].unitId = tableData[index].goodsUnitVoList[0].unitId;
                            tableData[index].times = tableData[index].goodsUnitVoList[0].times;
                        }
                    });



                    $(".number").unbind().bind("blur",function () {
                        processNumber_select(genNumber($(this).val()),$(this));
                    });

                    $(".numberAdd").unbind().bind("click",function () {
                        let $input=$(this).parent().find(".number");
                        processNumber_select(genNumber($input.val(),1), $input);
                    });

                    $(".numberSub").unbind().bind("click",function () {
                        let $input=$(this).parent().find(".number");
                        processNumber_select(genNumber($input.val(),2), $input);
                    });

                    $(".numberSn").unbind().bind("click",function () {
                        snIndex = $(this).parents('tr').data('index');
                        let goodsId = table.cache.table[snIndex].id;
                        console.log("houseId:${houseId}");
                        console.log("goodsId:"+goodsId);
                        if ("${numberBar}" == 1){
                            openHtmlDialog("管理序列号","${baseUrl}dialog/sn/import.action?type=2&houseId=${houseId}&goodsId="+goodsId, function (layero, index) {
                                var iframe = window[layero.find('iframe')[0]['name']];

                                let goodsSnList = layui.table.cache.table[snIndex].goodsSnList;
                                if (emptyList(goodsSnList)) {
                                    goodsSnList=[];
                                }
                                iframe.setDataToTable(goodsSnList,used_sn_map);
                            });
                        } else if ("${numberBar}" == 2){
                            openHtmlDialog("选择序列号","${baseUrl}dialog/sn/select.action?houseId=${houseId}&goodsId="+goodsId, function (layero, index) {
                                var iframe = window[layero.find('iframe')[0]['name']];

                                let goodsSnList = layui.table.cache.table[snIndex].goodsSnList;
                                if (emptyList(goodsSnList)) {
                                    goodsSnList=[];
                                }
                                iframe.setDataToTable(goodsSnList,used_sn_map);
                            });
                        }


                    });
                }
            });
        });

        /**
         * 开启sn号的商品，选择完序列号会回调这个
         *
         */
        function processSnSelect(data) {
            layui.table.cache.table[snIndex].goodsSnList = data;
            processNumber_select(data.length, $("tr[data-index='"+snIndex+"']").find(".number"));
        }

        function processSnImport(data) {
            layui.table.cache.table[snIndex].goodsSnList = data;
            processNumber_select(data.length, $("tr[data-index='"+snIndex+"']").find(".number"));
        }

        function processNumber_select(number, $input) {
            layui.use(['form', 'table'], function () {
                let $ = layui.jquery,
                    table = layui.table;

                let index = $input.parents('tr').data('index');
                let tableData = table.cache.table;

                <%--if ("${checkStock}" == 1) {--%>
                <%--    if (tableData[index].stockNum <= 0) {--%>
                <%--        //库存为0--%>
                <%--        tip("库存为零");--%>
                <%--        number = 0;--%>
                <%--    } else if (tableData[index].stockNum>0 && tableData[index].stockNum < number) {--%>
                <%--        tip("数量超过库存，自动修改到最大值");--%>
                <%--        number = tableData[index].stockNum>0 ? tableData[index].stockNum:0;--%>
                <%--    }--%>
                <%--}--%>

                //不是整数，但是单位有不支持小数
                let goodsUnitVo = genUnitVo(tableData[index].goodsUnitVoList, tableData[index].unitId);
                if (!isInteger(number) && goodsUnitVo.unit.point!=null && !goodsUnitVo.unit.point){
                    tip("此单位不允许小数，可以在单位中设置");
                    number = 0;
                }

                tableData[index].number = number;
                let amount = parseFloat(tableData[index].price) * number;
                tableData[index].amount = (amount);

                if (number == 0) {
                    $input.val("");
                    $input.html("");
                    deleteSelectedById(tableData[index].id);
                } else {
                    $input.val(number);
                    $input.html(number);
                    setDataToSelectedList(tableData[index]);
                }

                $("#selectNumber").html(getSelectedListLength());
            });
        }



        let selected_map = {};//已选择的商品列表 key是id, value是goods
        function getSelectedById(id) {
            if (selected_map[id] != undefined) {
                return selected_map[id]
            }
            return null;
        }

        function deleteSelectedById(id) {
            delete selected_map[id];
        }

        function  getSelectedListLength() {
            return Object.keys(selected_map).length;
        }

        function setDataToSelectedList(d) {
            selected_map[d.id] = d;
        }

        //已被使用的sn的map，key为goodsId
        let used_sn_map = {};
        function setUsedSnMap(usedSnMap) {
            used_sn_map = usedSnMap;
        }
    </script>

</html:header>
<body style="background-color: #ffffff">
<div style="padding: 20px;">
    <form class="layui-form layui-form-pane" action="">
        <input type="hidden" name="status" value="1">
        <input type="hidden" name="sn" value="${sn}">
        <div class="layui-form-item">

            <div class="layui-inline">
                <label class="layui-form-label">商品分类</label>
                <div class="layui-input-inline">
                    <select name="typeId"></select>
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">其他信息</label>
                <div class="layui-input-inline">
                    <input type="text" id="search" name="search" style="font-size: 12px;" placeholder="编号、名称、规格、属性、条形码" class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <a class="layui-btn" lay-submit="" lay-filter="search"><i class="layui-icon layui-icon-search"></i></a>
            </div>
        </div>
    </form>
    <hr>
    <table class="layui-hide" id="table" lay-filter="table"></table>
    <hr>
    <div style="overflow: hidden;">
        <div style="float:left">
            已选<span id="selectNumber" style="color: #FF5722">0</span>个商品
        </div>
        <div style="float: right">
            <button class="layui-btn" id="sure">确认</button>
            <button class="layui-btn layui-btn-primary" id="cancel">取消</button>
        </div>
    </div>

    <script type="text/html" id="numberBar" >
        <div class="numberDiv">
            <c:choose>
                <c:when test="${numberBar==1 || numberBar==2}">
                    {{# if(d.sn==true || d.shelfLife==true){ }}
                    <span class="number">{{getSelectedById(d.id)==null ? '':getSelectedById(d.id).number}}</span>
                    <span class="numberSn">sn</span>
                    {{# }else{ }}

                        <input type="number" name="number" value="{{getSelectedById(d.id)==null ? '':getSelectedById(d.id).number}}" class="layui-input number">

                        <div class="numberSub">减</div>
                        <div class="numberAdd">加</div>
                    {{# } }}
                </c:when>

                <c:otherwise>
                    <input type="number" name="number" value="{{getSelectedById(d.id)==null ? '':getSelectedById(d.id).number}}" class="layui-input number">
                    <div class="numberSub">减</div>
                    <div class="numberAdd">加</div>
                </c:otherwise>
            </c:choose>

        </div>
    </script>
</div>
</body>
<html:loading/>
</html>